<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/wellcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCate">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <tree-table class="treeTable"
       :data="categoriesList" :columns="columns"
       :selection-type="false" :expand-type="false"
       show-index index-text="#" border :show-row-hover="false">
        <template slot="isok" slot-scope="scope">
            <i v-if="scope.row.cat_deleted ===false" style="color: lightgreen" class="el-icon-success"></i>
            <i v-else class="el-icon-error" style="color:red"></i>
        </template>
        <template slot="order" slot-scope="scope">
            <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
            <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editCate(scope.row.cat_id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deltCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[3,5,10,15]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加信息弹框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addDialogVisible"
      width="50%"
      center :modal-append-to-body="false"
      :close-on-click-modal="false"
      @close="addDialogClose()">
      <!-- 表单信息 -->
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
            <el-cascader expandTrigger='hover' clearable change-on-select
            v-model="selectId"
            :options="paraCategoriesList"
            :props="cascaderProps"
            @change="selectChange">
            </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogCate()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改信息弹框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialogVisible"
      width="50%"
      center :modal-append-to-body="false"
      :close-on-click-modal="false"
      @close="editDialogClose">
      <!-- 表单信息 -->
      <el-form :model="editCateForm" :rules="addCateFormRules"  ref="editCateFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateName">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
    name:'Cate',
    data(){
        return {
            queryInfo:{
                type:3,
                pagenum:1,
                pagesize:5
            },
            categoriesList:[],    //数据列表
            total:0,
            // 表格数据
            columns:[
                {
                    label:'分类名称',
                    prop:'cat_name'
                },{
                   label:'是否有效',
                   type:'template',
                   template:'isok'
                },{
                   label:'排序',
                   type:'template',
                   template:'order'
                },{
                   label:'操作',
                   type:'template',
                   template:'opt'
                }
            ],
            addDialogVisible:false,
            addCateForm:{
                cat_name:'',
                cat_pid:0,
                cat_level:0
            },
            addCateFormRules:{
                cat_name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' }
                ],
            },
            paraCategoriesList:[],
            // 级联选择器的配置项
            cascaderProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            selectId:[],
            editDialogVisible:false,
            editCateForm:{
                cat_name:'',
                cat_id:0,
            }
        }
    },
    created(){
        this.getCategories();
    },
    methods:{
        // 获取商品分类列表
        async getCategories(){
            const {data:res} = await this.axios.get('categories',{params:this.queryInfo});
            // console.log(res);
            if(res.meta.status !==200){
                return this.$message.error('获取商品分类失败了~');
            }

            this.categoriesList = res.data.result;
            // console.log(this.categoriesList);
            this.total = res.data.total;
        },
        // 监听pagesize改变
        handleSizeChange(newpageS){
            this.queryInfo.pagesize = newpageS;
            this.getCategories();
        },
        // 监听pagenum的改变
        handleCurrentChange(newpageN){
            this.queryInfo.pagenum = newpageN;
            this.getCategories();
        },
        // 添加分类
        async addCate(){
            this.getParaCategories();
            this.addDialogVisible = true;
        },
        // 获取父级商品分类数据
        async getParaCategories(){
            const {data:res} = await this.axios.get('categories',{params:{type:2}});
            // console.log(res);
            if(res.meta.status !==200){
                return this.$message.error('获取父级商品分类失败了~');
            }

            this.paraCategoriesList = res.data;
        },
        // 级联选择器发生变化
        selectChange(){
            // console.log(this.selectId);
            // 判断添加分类有没有父级等级
            if(this.selectId.length > 0){
                // 父级分类id
                this.addCateForm.cat_pid = this.selectId[this.selectId.length-1];
                // 分类的等级
                this.addCateForm.cat_level = this.selectId.length;
                return;
            }else{
                this.addCateForm.cat_pid = 0;
                this.addCateForm.cat_level = 0;
            }
        },
        // 添加对话框关闭监听
        addDialogClose(){
            this.$refs.addCateFormRef.resetFields();
            this.selectId = [];
            this.addCateForm.cat_level = 0;
            this.addCateForm.cat_pid = 0;
        },
        // 添加对话框确定时间监听
        addDialogCate(){
            this.$refs.addCateFormRef.validate(async valid =>{
                if(!valid) return;
                const {data:res} = await this.axios.post('categories',this.addCateForm);
                // console.log(res);
                if(res.meta.status !==201){
                    return this.$message.error('添加商品分类失败了~');
                }
                this.$message.success('添加商品分类成功了~');
                this.getCategories()
            })
            this.addDialogVisible = false;
        },
        // 修改分类名称
        async editCate(id){
            // console.log(id);
            const {data:res} = await this.axios.get(`categories/${id}`);
            // console.log(res);
            if(res.meta.status !==200){
                return this.$message.error('获取商品分类信息失败了~');
            }
            this.editCateForm.cat_name = res.data.cat_name;
            this.editCateForm.cat_id =  res.data.cat_id;
            this.editDialogVisible = true;
        },
        // 分类名称修改提交事件
        editCateName(){
            this.$refs.editCateFormRef.validate(async valid =>{
                if(!valid) return;
                const id = this.editCateForm.cat_id;
                const cat_name = this.editCateForm.cat_name
                const {data:res} = await this.axios.put(`categories/${id}`,{cat_name});
                // console.log(res);
                if(res.meta.status !==200){
                    return this.$message.error('修改商品分类信息失败了~');
                }
                this.$message.success('修改商品分类信息成功了~');
                this.getCategories();
                this.editDialogVisible = false;
            })
        },
        // 编辑对话框关闭事件
        editDialogClose(){
            this.$refs.editCateFormRef.resetFields();
            this.editCateForm.cat_id = 0;
            this.editCateForm.cat_name = '';
        },
        // 删除分类
        deltCate(id){
            this.$confirm('此操作将永久删除该分类信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const {data:res} = await this.axios.delete(`categories/${id}`);
                if(res.meta.status !==200){
                    return this.$message.error('获取商品分类信息失败了~');
                }
                this.getCategories();
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        }
    }
}
</script>

<style lang="less" scoped>
.treeTable{
    margin-top: 15px;
}
.el-cascader{
    width:100%;
}

</style>